<?php
/**
 * Created by PhpStorm.
 * User: admin
 * Date: 2019/6/20
 * Time: 14:12
 */

namespace iBrand\Shop\Server\Service;


use iBrand\Component\Goods\Models\GoodsSpecRelation;
use iBrand\Component\Goods\Models\SpecsValue;
use iBrand\Component\Goods\Repositories\GoodsProductRepository;
use iBrand\Component\Goods\Repositories\GoodsRepository;

class WarehouseProductService
{
    protected $productRepository;
    protected $goodsRepository;

    public function __construct(GoodsProductRepository $goodsProductRepository,
                                GoodsRepository $goodsRepository)
    {
        $this->productRepository = $goodsProductRepository;
        $this->goodsRepository = $goodsRepository;
    }

    /**
     * 根据SKU编码获取prodcut数据
     * @param $sku
     * @return mixed
     */
    public function getProductDataBySku($sku)
    {
        $product = $this->productRepository->getProductBySku($sku);
        if ($product) {
            $specID = $product->specID;
            $tmpSpec = SpecsValue::find($specID[0]);
            if ($tmpSpec->spec_id == 1) {
                $size = $tmpSpec;
                $color = SpecsValue::find($specID[1]);
            } elseif ($tmpSpec->spec_id == 2) {
                $color = $tmpSpec;
                $size = SpecsValue::find($specID[1]);
            }
            $colorName = GoodsSpecRelation::where('goods_id', $product->goods_id)->where('spec_value_id', $color->id)->first()->alias;
            $product->colorId = $color->id;
            $product->colorName = $colorName;
            $product->sizeId = $size->id;
            $product->sizeName = $size->name;
        }

        return $product;
    }


    /**
     * 根据商品编码获取product数据
     * @param $code
     * @return mixed
     */
    public function getProductDataByCode($code)
    {
        $products = $this->productRepository->getProductByCode($code);
        if ($products->count()) {
            foreach ($products as $product) {
                $specID = $product->specID; 
                $tmpSpec = SpecsValue::find($specID[0]);
                if ($tmpSpec->spec_id == 1) {
                    $size = $tmpSpec;
                    $color = SpecsValue::find($specID[1]);
                } elseif ($tmpSpec->spec_id == 2) {
                    $color = $tmpSpec;
                    $size = SpecsValue::find($specID[1]);
                }
                $colorName = GoodsSpecRelation::where('goods_id', $product->goods_id)->where('spec_value_id', $color->id)->first()->alias;
                $product->colorId = $color->id;
                $product->colorName = $colorName;
                $product->sizeId = $size->id;
                $product->sizeName = $size->name;
            }
        }

        return $products;
    }


}